<?php
function __serialize($sObject) {
	$serialized = serialize($sObject);
   	return htmlentities($serialized,ENT_QUOTES);
}
//
function __unserialize($sObject) {
	$unserialized = stripslashes($sObject);
   	$unserialized = preg_replace('!s:(\d+):"(.*?)";!e', "'s:'.strlen('$2').':\"$2\";'", $unserialized );
   	return unserialize($unserialized);
}
//
function check_serialization( $string, &$errmsg ){
	$str = 's';
	$array = 'a';
	$integer = 'i';
	$any = '[^}]*?';
	$count = '\d+';
	$content = '"(?:\\\";|.)*?";';
	$open_tag = '\{';
	$close_tag = '\}';
	$parameter = "($str|$array|$integer|$any):($count)" . "(?:[:]($open_tag|$content)|[;])";            
	$preg = "/$parameter|($close_tag)/";
	if(!preg_match_all( $preg, $string, $matches )){            
		$errmsg = 'not a serialized string';
		return false;
	}    
	$open_arrays = 0;
	foreach( $matches[1] AS $key => $value ){
	    if(!empty( $value ) && ( $value != $array xor $value != $str xor $value != $integer )){
	        $errmsg = 'undefined datatype';
	        return false;
	    }
	    if( $value == $array ){
	        $open_arrays++;                                
	        if( $matches[3][$key] != '{' ) {
	            $errmsg = 'open tag expected';
	            return false;
	        }
	    }
	    if( $value == '' ){
	        if( $matches[4][$key] != '}' ){
	            $errmsg = 'close tag expected';
	            return false;
	        }
	        $open_arrays--;
	    }
	    if( $value == $str ){
	        $aVar = ltrim( $matches[3][$key], '"' );
	        $aVar = rtrim( $aVar, '";' );
	        if( strlen( $aVar ) != $matches[2][$key] ) 
	        {
	            $errmsg = 'stringlen for string not match';
	            return false;
	        }
	    }
	    if( $value == $integer ){
	        if( !empty( $matches[3][$key] ) ) 
	        {
	            $errmsg = 'unexpected data';
	            return false;
	        }
	        if( !is_integer( (int)$matches[2][$key] ) ) 
	        {
	            $errmsg = 'integer expected';
	            return false;
	        }
	    }
	}        
	if( $open_arrays != 0 ){
	    $errmsg = 'wrong setted arrays';
	    return false;
	}
   return true;
}

?>